const fs = require('fs');
const logger = require('./log')('Routes');

/**
 * 动态加载路由
 */
class Routes {
    
    constructor(app, path) {
        this._app = app;
        this._path = path || './app';
    
        if (!this._app) {
            logger.error("app is undefined");
        }
        logger.info("reoute loading...")
        this.listDir(this._path);
    }
    
    /**
     * 遍历搜索routes文件夹
     * @param {string} dir 
     */
    listDir(dir) {
        let fileList = fs.readdirSync(dir, 'utf-8');
        for (let i = 0; i < fileList.length; i++) {
            let file = dir + "/" + fileList[i];
            let stat = fs.lstatSync(file);
            if (stat.isDirectory() && fileList[i] === 'routes') {
                this.loadRouteDir(file)
            } else if (stat.isDirectory()) {
                this.listDir(file);
            }
        }
    }

    /**
     * 查找routes文件夹下所有js文件
     * @param {*} dir 
     */
    loadRouteDir(dir) {
        let fileList = fs.readdirSync(dir, 'utf-8');
        for (let i = 0; i < fileList.length; i++) {
            let file = dir + "/" + fileList[i];
            let stat = fs.lstatSync(file);
            if (stat.isDirectory()) {
                this.loadRouteDir(file + '/');
            } else {
                this.loadRoute(file)
            }
        }
    }

    /**
     * 加载路由
     * @param {string} routeFile 
     */
    loadRoute(routeFile) {
        logger.info(routeFile);
        let routeFilePath = routeFile.substring(0, routeFile.lastIndexOf("."));
        let route = require(routeFilePath);
        if (route.basePath) {
            this._app.use(route.basePath, route);
        } else {
            this._app.use(route);
        }
    }
    
}

module.exports = Routes